"""
:param
    none
:return
    none
use camera to make vedio
"""""
import _thread
import os
import numpy as np
from app.kernal.framehandle import RTSCapture
import cv2
import time, datetime
import threading


class Camera:

    def __init__(self):
        self.__starttime = datetime.datetime.today().strftime('%Y%m%d%H%M%S')
        self.rtscap = RTSCapture.create(0, cv2.CAP_DSHOW)
        self.fourcc = cv2.VideoWriter_fourcc(*'mp4v')
        self.fourccavi = cv2.VideoWriter_fourcc(*'XVID')
        # set the url
        self.__url = 'monitor' + self.__starttime +'.avi'
        self.__urlarr = {}
        self.__switch = False
        self.outarr = []

    def startcamera(self,newurl):
        'return starttime'
        # init camera
        try:
            self.rtscap.start_read()
            self.delurl(self.__url)
        except:
            print("don't have such")
        self.__url = newurl
        self.addurl(newurl)
        #cap = cv2.VideoCapture(0)

        #out = cv2.VideoWriter(newurl, self.fourcc, 20.0, (640, 480))
        #self.outarr.append(out)
        # write frame to every file in uelarr
        if(self.isOn()):
            print("started")
            return self.__starttime
        try:
            t = threading.Thread(target=self.allframe, args=(self.rtscap,self.fourcc))
            t.start()
            self.turnOn()
        except:
            print("thread beginerro")
        print("startok")
        return self.__starttime

    def turnOn(self):
        self.__switch = True

    def turnOff(self):
        self.__switch = False

    def isOn(self):
        return self.__switch

    def setstarttime(self, newstarttime):
        self.__starttime = newstarttime
        return True

    def addurl(self, newurl,type=0):
        #self.__urlarr.append(newurl)
        if type == 0:
            out = cv2.VideoWriter(newurl, self.fourcc, 30.0, (640, 480))
        else:
            out = cv2.VideoWriter(newurl, self.fourccavi, 30.0, (640, 480))
        #self.outarr.append(out)
        self.__urlarr[newurl]=out
        print("add"+newurl)
        return True

    def delurl(self, delurl):
        self.turnOff()
        out = self.__urlarr[delurl]
        out.release()
        self.__urlarr.pop(delurl)
        self.turnOn()
        return True

    def getstarttime(self):
        return self.__starttime

    def geturl(self):
        return self.__url

    def allframe(self, rstcap, fourcc):
        # return the current frame
        if(rstcap.isStarted()):
            print("op")
        else:
            print("not")
        #out = cv2.VideoWriter(furl, fourcc, 20.0, (640, 480))
        while (rstcap.isOpened() and self.isOn() and self.__urlarr):
            #print("catch")
            ret,frame = rstcap.read_latest_frame()
            if ret == True :
                #for furl in self.__urlarr:
                    # set out url
                    try:
                        #cv2.imwrite("./static/vedio/direact/veo100.jpg", frame)
                        for key in self.__urlarr:
                            #print("frame catch")
                            outer = self.__urlarr.get(key)
                            outer.write(frame)
                    except:
                        print("edit")
            else:
                break


camera = Camera()


'''

# use the camera from local
cap = cv2.VideoCapture(0)

# define the codec and creact VeidioWriter object
# user FourCC code
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('output.avi', fourcc, 20.0, (640, 480))
while (cap.isOpened()):
    ret, frame = cap.read()
    if ret == True:
        # just turn the picture
        # frame = cv2.flip(frame,0)

        # write the flipped frame
        out.write(frame)

        # if test acp delet the window here and test again
        cv2.imshow('frame', frame)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    else:
        break

# Release evething if job is finished
cap.release()
out.release()
cv2.destroyAllWindows()
'''
# """
# :param
#     none
# :return
#     none
# use camera to make vedio
# """""
# import numpy as np
# import cv2
# import time, datetime
#
#
# class Camera:
#
#
#     def __init__(self):
#         self.__starttime =  time.asctime( time.localtime(time.time()) )
#         #set the url
#         self.__urlarr = [self.__url]
#         self.__switch = False
#
#     def start(self):
#         'return starttime'
#         #creact a vedio file here
#
#         #write frame to every file in uelarr
#         while(self.__switch == True):
#             # write frame
#             break
#
#         return self.__starttime
#
#     def turnOn(self):
#         self.__switch = True
#
#     def turnOff(self):
#         self.__switch = False
#
#     def isOn(self):
#         return self.__switch
#
#     def setstarttime(self,newstarttime):
#         self.__starttime = newstarttime
#         return True
#
#     def seturl(self,newurl):
#         self.__url = newurl
#         return True
#
#     def getstarttime(self):
#         return self.__starttime
#
#     def geturl(self):
#         return self.__url
#
#     def allframe(self):
#         #return the current frame
#         pass
#
# camera = Camera()
# '''
#
# # use the camera from local
# cap = cv2.VideoCapture(0)
#
# # define the codec and creact VeidioWriter object
# # user FourCC code
# fourcc = cv2.VideoWriter_fourcc(*'XVID')
# out = cv2.VideoWriter('output.avi', fourcc, 20.0, (640, 480))
# while (cap.isOpened()):
#     ret, frame = cap.read()
#     if ret == True:
#         # just turn the picture
#         # frame = cv2.flip(frame,0)
#
#         # write the flipped frame
#         out.write(frame)
#
#         # if test acp delet the window here and test again
#         cv2.imshow('frame', frame)
#         if cv2.waitKey(1) & 0xFF == ord('q'):
#             break
#     else:
#         break
#
# # Release evething if job is finished
# cap.release()
# out.release()
# cv2.destroyAllWindows()
# '''

